<script setup lang="ts">
import axios from 'axios'

interface FeedItem {
  id: number
  content: string
  image: string
  width: number
  height: number
}

// 数据相关
const leftItems = ref<FeedItem[]>([])
const rightItems = ref<FeedItem[]>([])
const page = ref(1)
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)
const imgShow = ref(false)
// 布局相关
const containerWidth = ref(0)
const columnWidth = ref(0)

// 获取容器宽度
const updateLayout = () => {
  const container = document.querySelector('.feed-container')
  if (container) {
    containerWidth.value = container.clientWidth
    columnWidth.value = (containerWidth.value - 10) / 2 // 10px间距
  }
}

// 处理不同API参数格式
const getRequestParams = () => {
  const params: Record<string, any> = {}
  // 示例：支持两种参数格式
  if (page.value === 1) {
    params.format = 'v1'
    params.page = 1
    params.size = 10
  } else {
    params.format = 'v2'
    params.offset = (page.value - 1) * 10
    params.limit = 10
  }

  return params
}
// 图片预览相关
const index = ref(0);
// 获取数据
const fetchData = async () => {
  if (!hasMore.value || loading.value) return
  loading.value = true
  try {
    const params = getRequestParams()
    const res = await axios.get('/api/list', { params })
    const { list } = res.data.data
    if (list.length === 0) {
      hasMore.value = false
      return
    }
    distributeItems(list)
    page.value++
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 分配元素到列
const distributeItems = (items: FeedItem[]) => {
  console.log('分配元素到列', items)
  items.forEach(item => {
    const leftHeight = leftItems.value.reduce((sum, i) => sum + getItemHeight(i), 0)
    const rightHeight = rightItems.value.reduce((sum, i) => sum + getItemHeight(i), 0)
    if (leftHeight <= rightHeight) {
      leftItems.value.push(item)
    } else {
      rightItems.value.push(item)
    }
  })
}

// 计算项目高度（根据宽高比）
const getItemHeight = (item: FeedItem) => {
  return (item.height / item.width) * columnWidth.value + 20 // 40为内容区域预估高度
}

// 重置数据并重新获取
const resetAndFetch = () => {
  page.value = 1
  leftItems.value = []
  rightItems.value = []
  hasMore.value = true
  fetchData()
}
const images = ref<any[]>([])

const currentClick = (image: string) => {
  images.value = [image]
  imgShow.value = true
  index.value = 0
}
// 生命周期
onMounted(() => {
  updateLayout()
  fetchData()
})
// 下拉刷新
const onRefresh = () => {
  loading.value = true;

  setTimeout(() => {
    console.log('刷新成功');
    loading.value = false;

    // 刷新后重置列表
    resetAndFetch();
  }, 1000);
};
</script>

<template>
  <navigationBar>
    <h1>首页</h1>
  </navigationBar>
  <Container>
    <div class="container">
      <!-- 下拉刷新提示 -->
      <div v-show="refreshing" class="refresh-indicator">
        <div class="loading-spinner"></div>
      </div>
      <!-- 瀑布流容器 -->
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
        <div class="feed-container">
          <!-- 左列 -->
          <div class="column">
            <div v-for="item in leftItems" :key="item.id" class="feed-item">
              <img :src="item.image" :style="{ width: '100%', height: '90%' }" alt="content"
                @click="currentClick(item.image)">
              <div class="content">{{ item.content }}</div>
            </div>
          </div>

          <!-- 右列 -->
          <div class="column">
            <div v-for="item in rightItems" :key="item.id" class="feed-item">
              <img :src="item.image" :style="{ width: '100%', height: '90%' }" alt="content"
                @click="currentClick(item.image)">
              <div class="content">{{ item.content }}</div>

            </div>

          </div>
        </div>
      </van-pull-refresh>
      <van-image-preview v-model:show="imgShow" :images="images" :closeable="true">
        <template v-slot:index>第{{ index + 1 }}页</template>
      </van-image-preview>
      <!-- 没有更多数据 -->
      <div class="end-message" v-if="hasMore">
        <i class="van-icon van-icon-checked"></i> 已经到底啦
      </div>
    </div>
  </Container>
</template>

<style scoped>
.container {
  position: relative;
  padding: 0 10px;
}

.feed-container {
  display: flex;
  gap: 10px;
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.feed-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.feed-item img {
  width: 100%;
  object-fit: cover;
}

.content {
  padding: 10px;
  font-size: 14px;
}

.refresh-indicator,
.loading-indicator {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #ccc;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.no-more {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>